package com.wesley.mybatis.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.wesley.mybatis.entity.User;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.io.IOException;

/**
 *  MyBatis与Spring整合Config
 *
 * @author WangPanYong
 * @since 2021/10/13 11:05
 */
@Configuration
@MapperScan(basePackages = {"com.wesley.mybatis.mapper"})
@ComponentScan(basePackages = {"com.wesley.mybatis"})
@Repository
public class MyBatisConfig {

    @Bean
    public SqlSessionFactoryBean sqlSessionFactory( ) throws IOException {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource());
        // 设置 MyBatis 配置文件路径
        factoryBean.setConfigLocation(new ClassPathResource("mybatis-spring-config.xml"));
        // 设置 SQL 映射文件路径
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/*.xml"));
        factoryBean.setTypeAliases(User.class);
        return factoryBean;
    }

    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUsername("root");
        dataSource.setPassword("root123");
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/samples?characterEncoding=utf8");
        return dataSource;
    }


}
